/*
 * CharNode.cpp
 *
 *  Created on: 2017年6月20日
 *      Author: heqian
 */

#include "CharNode.h"

namespace mmseg {

CharNode::CharNode() :
		pos(un), mKey(0), strKey((char*) &mKey), mNode(nullptr), mNext(nullptr), mSize(1), isWord(false) {
}

CharNode::~CharNode() {
	CharNode* next = mNode;
	CharNode* temp;
	while (next) {
		temp = next->getNext();
		delete next;
		next = temp;
	}
	mNode = nullptr;
}

const string& CharNode::getOther() const {
	return other;
}

void CharNode::setOther(const string& other) {
	this->other = other;
}

EnumPos CharNode::getPos() {
	return pos;
}

void CharNode::setPos(EnumPos pos) {
	this->pos = pos;
}

CharNode* CharNode::find(UTF_8 key, bool isNew) {
	CharNode* next = this;
	CharNode* up;
	while (next) {
		if (key == next->mKey)
			return next;
		up = next;
		next = next->mNext;
	}

	if (isNew) {
		next = new CharNode();
		next->mKey = key;
		up->mNext = next;
		mSize++;
	}

	return next;
}

CharNode** CharNode::getNode() {
	return &mNode;
}

CharNode* CharNode::getNext() {
	return mNext;
}

UTF_8 CharNode::getKey() const {
	return mKey;
}

void CharNode::setKey(UTF_8 key) {
	mKey = key;
}

int CharNode::getSize() {
	return mSize;
}

int CharNode::maxMatch(const char* str, int num, CharNode** out) {
	int i = 0;
	UTF_8 key;
	int size = 0;
	char temp;
	CharNode* node = mNode;

	while (i < num && node) {
		temp = str[i];
		size = 1;
		if (temp & 0x80) {
			temp <<= 1;
			do {
				temp <<= 1;
				++size;
			} while (temp & 0x80);
		}

		key = 0;
		memcpy(&key, str + i, size);
		UTF_SIZE(key) = size;

		if ((node = node->find(key, false))) {
			if (!node->isIsWord())
				break;

			*out = node;
			i += size;
			node = node->mNode;
		}
	}
	return i;
}

bool CharNode::isIsWord() const {
	return isWord;
}

void CharNode::setIsWord(bool isWord) {
	this->isWord = isWord;
}

}
/* namespace mmseg */
